﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using UcAsp.Net.Extract.Plug.Vogue.BLL;
using UcAsp.Net.Extract.Plug.Vogue.Model;
using UcAsp.Net.Interface;
using System.Text.RegularExpressions;
using System.Threading;
namespace UcAsp.Net.Extract.Plug.Vogue
{
    public partial class UcAspControl : UserControl, IExtract
    {
        ///<div\s*class="ThList-contimgbox"><a href="(?<url>(.)*)"\s*title="(?<title>(.)*)"\s*target
        private delegate void DelegateUpdate(string i);
        private DateTime _adddatetime = DateTime.Now;
        private Thread t ;
        #region 属性
        /// <summary>
        /// 常规项
        /// </summary>
        /// 
        public string Security { get; set; }
        public string Image { get; set; }
        public int ID { get; set; }
        public string Title { get; set; }
        public string Tag { get; set; }
        public string IconUrl { get; set; }
        public string ArticleContent { get; set; }
        public string MetaKeyword { get; set; }
        public string MetaDescrition { get; set; }
        public string Description { get; set; }
        public DateTime AddDatetime { get { return this._adddatetime; } set { this._adddatetime = value; } }
        public bool IsRelease { get; set; }
        public bool IsRecommend { get; set; }
        public int Hot { get; set; }
        public int Rate { get; set; }
        public int CategorieID { get; set; }
        public string ShowPath { get; set; }
        public string ViewsTemp { get; set; }
        public int UserID { get; set; }
        public int Rank { get; set; }

        /// <summary>
        /// 可变文字项
        /// </summary>
        public string Note1 { get; set; }
        public string Note2 { get; set; }
        public string Note3 { get; set; }
        public string Note4 { get; set; }
        public string Note5 { get; set; }
        public string Note6 { get; set; }
        public string Note7 { get; set; }
        public string Note8 { get; set; }
        public string Note9 { get; set; }
        /// <summary>
        /// 可变数组项
        /// </summary>
        public int Int1 { get; set; }
        public int Int2 { get; set; }
        public int Int3 { get; set; }
        public int Int4 { get; set; }
        public int Int5 { get; set; }


        public double Float1 { get; set; }
        public double Float2 { get; set; }
        public double Float3 { get; set; }
        public double Float4 { get; set; }
        public double Float5 { get; set; }


        public DateTime Date1 { get; set; }
        public DateTime Date2 { get; set; }
        public DateTime Date3 { get; set; }
        public DateTime Date4 { get; set; }
        public DateTime Date5 { get; set; }
        public DateTime Date6 { get; set; }
        public DateTime Date7 { get; set; }
        public DateTime Date8 { get; set; }
        public int PageCount { get; set; }
        #endregion
        public virtual bool Execute(object id)
        { return true; }
        public virtual object Init() { return new bool(); }
        public event EventHandler Save;
        public event EventHandler SavePage;
        public event EventHandler SaveImage;
        public UcAspControl()
        {
            InitializeComponent();
            labNumber.Text = "";
            label1.Hide();
        }

        private void UcAspControl_Load(object sender, EventArgs e)
        {
            List<Model.Config> list = BLL.Config.GetListConfig;
            lbConfig.DataSource = list;
            lbConfig.DisplayMember = "DefinedTitle";
            lbConfig.ValueMember = "DefinedName";

            this.Width = this.Parent.Width;
            this.Height = this.Parent.Height;
        }

        private void btnAuto_Click(object sender, EventArgs e)
        {
            if (lbConfig.SelectedValue != null)
            {
                label1.Show();
                ParameterizedThreadStart start = new ParameterizedThreadStart(UpdateData);
                t = new Thread(start);
                t.Name = "updatedata";
                t.Start(lbConfig.SelectedValue.ToString());
                //UpdateData(lbConfig.SelectedValue.ToString());
            }
            else
            {
                MessageBox.Show("请选择更新类目");
            }
        }
        private void UpdateUI(string i)
        {
            labNumber.Text = "已经更新" + i.ToString() + "条";
        }
        public void UpdateData(object path)
        {
            Model.FilesConfig config = BLL.FilesConfig.GetFilesConfig(path.ToString());
            int pagecount = 0;
            for (int p = config.PageNumber; p >= 0; p--)
            {
                string urlcongent = string.Empty;
                if (p != 0)
                {
                    urlcongent = HttpWebClient.GetString(config.PageUrl.Replace("{page}", p.ToString()));
                }
                else
                {
                    urlcongent = HttpWebClient.GetString(config.Url);
                }
              //  urlcongent = HttpWebClient.GetString(config.Url);
                RegexOptions options = RegexOptions.None;
                Regex regex = new Regex(config.URLReg, options);
                MatchCollection matches = regex.Matches(urlcongent);
                AddDatetime = DateTime.Now; CategorieID = config.CategorieID; IsRelease = true; Image = config.ImageReg;
                for (int j = 0; j < matches.Count; j++)
                {
                    pagecount++;
                    if (p == 0) {
                        this.Invoke(new DelegateUpdate(UpdateUI), "END");
                    }
                    else
                    {
                        this.Invoke(new DelegateUpdate(UpdateUI), pagecount.ToString());
                    }
                    string pageurl = matches[j].Groups["url"].Value;
                    if (pageurl.IndexOf("http://", 0) < 0)
                    {
                        pageurl = config.RootPath;
                    }
                    string pagecontent = HttpWebClient.GetString(pageurl);
                    if (pageurl.IndexOf("pic", 0) > 0)
                    {

                        //标题
                        Regex pageregex = new Regex(config.PicTitleReg, options);
                        Match match = pageregex.Match(pagecontent);
                        string title = match.Groups["title"].Value;
                        Title = title;
                        //内容
                        Regex contentregex = new Regex(config.PicContentReg, options);
                        Match contentmatch = contentregex.Match(pagecontent);
                        string content = contentmatch.Groups["content"].Value;
                        
                        Regex pic = new Regex(config.PicImageReg, options);
                        MatchCollection picmatch = pic.Matches(pagecontent);

                        Regex picdescriptionreg = new Regex(config.PicDescription, options);
                        MatchCollection picdescription = picdescriptionreg.Matches(pagecontent);
                        PageCount = picmatch.Count + 1;
                        //if (picdescription.Count != picmatch.Count)
                        //    continue;
                        for (int m = 0; m < picmatch.Count; m++)
                        {
                            string imageurl = picmatch[m].Groups["url"].Value;
                             IconUrl = imageurl;
                             try
                             {
                                 string imagedescription = picdescription[m].Groups["content"].Value;
                                 ArticleContent = ClearCode(imagedescription, config.ClearReg);
                             }
                             catch { }
                           

                            if (m == 0)
                            {
                                if (Save != null)
                                {
                                    Save(this, EventArgs.Empty);
                                }
                            }
                            else
                            {
                                Int1 = m + 2;
                                if (SavePage != null)
                                {
                                    SavePage(this, EventArgs.Empty);
                                }
                            }

                        }
                        ID = 0;
                    }
                    //图片内容
                    else
                    {
                      
                        //标题
                        Regex pageregex = new Regex(config.TitleReg, options);
                        Match match = pageregex.Match(pagecontent);
                        string title = match.Groups["title"].Value;
                        Title = title;
                        //内容
                        Regex contentregex = new Regex(config.ContentReg, options);
                        Match contentmatch = contentregex.Match(pagecontent);
                        string content = contentmatch.Groups["content"].Value;
                        if (content.Length < 10)
                            continue;
                        // richTextBox1.Text = richTextBox1.Text + "\r" + ClearCode(content, config.ClearReg);
                        ArticleContent = ClearCode(content, config.ClearReg);
                        //分页页码
                        Regex pagenumberregex = new Regex(config.PageReg, options);
                        MatchCollection pagenumbermatch = pagenumberregex.Matches(pagecontent);
                        if (Save != null)
                        {
                            Save(this, EventArgs.Empty);
                        }
                        List<int> pageint = new List<int>();
                        PageCount = pagenumbermatch.Count + 1;
                        if (PageCount > 1)
                        {
                            for (int i = 0; i < pagenumbermatch.Count; i++)
                            {
                                int number = int.Parse(pagenumbermatch[i].Groups["number"].Value);
                                pageint.Add(number);
                            }
                            for (int i = 2; i < pageint.Max(); i++)
                            {
                                string pagenuber = pagenumbermatch[0].Groups["url"].Value;

                                Int1 = i;
                                SmallContent(pagenuber.ToLower().Replace(".html", "-" + i + ".html"), config);
                            }


                        }

                        
                        ID = 0;
                        
                        // richTextBox1.Text = richTextBox1.Text + "\r" + ClearCode(content, config.ClearReg);
                        //ArticleContent = ClearCode(content, config.ClearReg);

                    }
                }
            }
        }
        private void SmallContent(string url, Model.FilesConfig config)
        {
            RegexOptions options = RegexOptions.None;
            string pagecontent = HttpWebClient.GetString(url);
            //标题

            Regex pageregex = new Regex(config.TitleReg, options);
            Match match = pageregex.Match(pagecontent);
            string title = match.Groups["title"].Value;
            Title = title;
            //内容
            Regex contentregex = new Regex(config.ContentReg, options);
            Match contentmatch = contentregex.Match(pagecontent);
            string content = ClearCode(contentmatch.Groups["content"].Value, config.ClearReg);
            // richTextBox1.Text = richTextBox1.Text + "\r" + content;
            ArticleContent = content;

            if (SavePage != null)
            {
                SavePage(this, EventArgs.Empty);
            }
        }
        /// <summary>
        /// 清理内容中的多余代码
        /// </summary>
        /// <param name="cotent"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private string ClearCode(string cotent, string code)
        {
            RegexOptions options = RegexOptions.None;
            Regex regex = new Regex(code, options);
            string input = cotent;
            string replacement = "";
            string result = regex.Replace(input, replacement);

            // TODO: Do something with result
            return result;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (t != null)
            {
                t.Abort();
            }
        }

    }
}
